import { useContext, useEffect } from "react";
import { WebsiteContext } from "../../contexts/Website";
import Crowd from "./Crowd";
import Friend from "./Friend";
import { MemberContext } from "../../contexts/Member";
import dayjs from "dayjs";
import { FriendType } from "../../components/Member";
import { RoomType } from "../../components/Room";

export default function Room() {
    const { setWebsite } = useContext(WebsiteContext);
    const { rooms, friends } = useContext(MemberContext);

    useEffect(() => {
        setWebsite({title: '微信'});
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const chats = [...(rooms || []), ...(friends || [])]
        .map((item) => ({...item, createdAt: [...(item.messages || [])].pop()?.createdAt || ''}))
        .sort((a, b) => dayjs(b.createdAt || '1').unix() - dayjs(a.createdAt || '1').unix());

    return <>
        <div className="flex flex-col divide-y border-b bg-gray-100 min-h-full">
            {
                chats.map((chat: FriendType | RoomType) => {
                    if('chatId' in chat) {
                        return <Friend key={`friend-${chat.chatId}`} friend={chat} />;
                    }
                    return <Crowd key={`room-${chat.id}`} room={chat} />;
                })
            }
        </div>
    </>
}
